<?php
/**
 * PHP Template.
 */
class classUsers  extends phpajax{
    private $user_sess_value='';
    
    function input(){
        //user menu and operations
        aread("User_Operation");
        //user login
        aread("User_LoginForm_Login");
        aread("User_LoginForm_Passwd");
        //register and update form data
        aread("User_RegisterForm_U_Organisation");
        aread("User_RegisterForm_U_Name");
        aread("User_RegisterForm_U_Surname");
        aread("User_RegisterForm_U_City");
        aread("User_RegisterForm_U_Street");
        aread("User_RegisterForm_U_PostID");
        aread("User_RegisterForm_U_Mobile");
        aread("User_RegisterForm_U_Phone");
        aread("User_RegisterForm_U_Email");
        aread("User_RegisterForm_U_BirthDate");
        aread("User_RegisterForm_U_ICO");
        aread("User_RegisterForm_U_DIC");
        aread("User_RegisterForm_U_Nick");
        aread("User_RegisterForm_U_Passwd");
        aread("User_RegisterForm_U_Passwd2");
        aread("User_RegisterForm_U_OldPassword");
        aread("User_RegisterForm_U_NewPassword");
        aread("User_RegisterForm_U_NewPassword2");
    }
    
    function loading(){}
    
    function main(){
        //user menu and operations
        $sUserOperation = &$this->User_Operation;
        
        $_Window = new classWindow();
        $_Form   = new classUsersForms();
        $_user_sess = new classSessions();
        
        //---------------------------open session-------------------------------
        $this->user_sess_value = $_user_sess->Open(_SESS_USER_);
        //----------------------------------------------------------------------
        
        //----------------------------------------------------------------------
        //Retrieve login data and check login in database
        if($sUserOperation == 'jsd_UO_CheckLogin'){
            $_UsersData = new classUsersData();
            $_Input = new classInput();            
            
            $iUID = $_UsersData->LoginCheck(
                $_Input->Sterilize(trim($this->User_LoginForm_Login)),
                $_Input->Sterilize(trim($this->User_LoginForm_Passwd))            
            );
            
            if($iUID>0 and is_numeric($iUID)){
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getLoginSuccessfullInfo()));
                $this->user_sess_value = $iUID;
            }
            else
                aprint("User_LoginForm_ResultContainer",_i18n_user_INCORRECT_LOGIN_NAME_OR_PASSWORD_);
        }
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //LogOut
        if($sUserOperation == 'jsd_UO_LogOut'){
            $this->user_sess_value = '';
            aprint("middle_container","<center>"._i18n_user_USER_IS_UNLOGGED_."</center>");
        }
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //show user and operations main menu:
        if($this->user_sess_value>0 and is_numeric($this->user_sess_value))
            aprint("users_container",$this->getUserMenu(true)); //menu for logged user
        else
            aprint("users_container",$this->getUserMenu(false));//menu for unlogged user 
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //Show login form
        if($sUserOperation == 'jsd_UO_ShowLoginForm')
            aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getLoginForm()));
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //close window with forms
        if($sUserOperation == 'jsd_UO_CloseWindow'){
            $_Products = new classProduct();
            aprint('flow_container2','');
            aprint('middle_container',$_Products->getProducts());
        }
        //----------------------------------------------------------------------    
        
            
        //----------------------------------------------------------------------
        //show form for user registring
        if($sUserOperation == 'jsd_UO_ShowRegisterForm')
            aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getRegisterForm()));
        //----------------------------------------------------------------------


        //----------------------------------------------------------------------
        //show form for new password sending
        if($sUserOperation == 'jsd_UO_ForgottenPassword_FormShow')
            aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getForgottenPasswdForm()));
        //----------------------------------------------------------------------


        //----------------------------------------------------------------------
        //send new password to e-mail
        if($sUserOperation == 'jsd_UO_ForgottenPassword_SentEmail' and trim($this->User_RegisterForm_U_Nick)!=''){
            $_Input = new classInput();
            $sending_result = self::sendEmailWithNewPassword($_Input->Sterilize(trim($this->User_RegisterForm_U_Nick)));

            if($sending_result=='_SUCCESSFULL_')
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getForgottenPasswd_Email_Successfull_Sent()));
            else{
                if($sending_result=='_USER_DONT_EXISTS_')
                    aprint('User_ForgottenPasswdForm_ResultContainer',_i18n_user_ENTERED_USERNAME_HASNT_REGISTERED_);
                if($sending_result=='_DUPLICITY_ERROR_')
                    aprint('User_ForgottenPasswdForm_ResultContainer',_i18n_user_PASSWORD_HAS_SENT_YET_CHECK_YOUR_EMAIL_ACCOUNT_);
                if($sending_result=='_NO_EMAIL_ADDRESS_')
                    aprint('User_ForgottenPasswdForm_ResultContainer',_i18n_user_FOR_ENTERED_USERNAME_HASNT_REGISTERED_EMAIL_ADDRESS_CONTACT_SHOP_ADMIN);
            }
        }
        //----------------------------------------------------------------------


        
        
        //----------------------------------------------------------------------
        //Retrieve register information, check data integrity and try to save data into DB
        if($sUserOperation == 'jsd_UO_RegisterUser'){
            $aasValues    = $this->makeAssocArrayForUser();
            $bTestResult  = $this->TestBeforeSaving($aasValues);        
            if ($bTestResult==1){
                $_UserData = new classUsersData();
                $iUID = $_UserData->Insert($aasValues);
                $this->user_sess_value = $iUID;
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getInsertSuccessfullInfo()));
            }
            else {
                switch($bTestResult){
                    case 5: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_ALL_REQUIRED_VALUES_ARE_NOT_TYPED_); break;
                    case 4: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_YOU_HAVE_TO_TYPE_LEAST_ONE_OF_FIELDS_MARKED_BY_2STARS_); break;
                    case 3: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_PASSWORD_AND_REPEAT_PASSWORD_DO_NOT_MATCH_); break;
                    case 2: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_THIS_LOGIN_NAME_IS_ALREADY_REGISTERED_); break;
                }
                
            }
        }
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //show form for user info update
        if($sUserOperation == 'jsd_UO_ShowUserUpdateForm'){
            $_UserData = new classUsersData();
            if($this->user_sess_value>0 and is_numeric($this->user_sess_value))
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getUserInfoUpdateForm($_UserData->getUserInfo($this->user_sess_value))));
        }
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //Retrieve register information, check data integrity and try to update data in DB
        if($sUserOperation == 'jsd_UO_UpdateUserInfo'){
            $aasValues    = $this->makeAssocArrayForUser();
            $bTestResult  = $this->TestBeforeUserInfoUpdating($aasValues);        
            if ($bTestResult==1 and $this->user_sess_value>0 and is_numeric($this->user_sess_value)){
                //update data in DB
                $_UserData = new classUsersData();
                $_UserData->Update($aasValues, $this->user_sess_value);
                //aprint('User_RegisterForm_Test_Result_Container','Udaje su OK');
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getUpdateSuccessfullInfo()));
            }
            else {
                switch($bTestResult){
                    case 5: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_ALL_REQUIRED_VALUES_ARE_NOT_TYPED_); break;
                    case 4: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_YOU_HAVE_TO_TYPE_LEAST_ONE_OF_FIELDS_MARKED_BY_2STARS_); break;
                }
                
            }
        }
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //show form for password update
        if($sUserOperation == 'jsd_UO_ShowPasswordUpdateForm'){
            $_UserData = new classUsersData();
            if($this->user_sess_value>0 and is_numeric($this->user_sess_value))
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getUserPasswordUpdateForm()));
        }
        //----------------------------------------------------------------------
        
        
        //----------------------------------------------------------------------
        //Retrieve register information, check data integrity and try to update data in DB
        if($sUserOperation == 'jsd_UO_UpdateUserPassword'){
            $sOldPassword  = trim($this->User_RegisterForm_U_OldPassword);
            $sNewPassword  = trim($this->User_RegisterForm_U_NewPassword);
            $sNewPassword2 = trim($this->User_RegisterForm_U_NewPassword2);
            //test values
            if($this->user_sess_value>0 and is_numeric($this->user_sess_value))
                $bTestResult  = $this->TestBeforeUserPasswordUpdating($this->user_sess_value,$sOldPassword,$sNewPassword,$sNewPassword2);
            if ($bTestResult==1 and $this->user_sess_value>0 and is_numeric($this->user_sess_value)){
                //update data in DB
                $_UserData = new classUsersData();
                $_UserData->Update_Password($this->user_sess_value, $sNewPassword);
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getUpdatePasswordSuccessfullInfo()));
            }
            else {
                switch($bTestResult){
                    case 6: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_YOU_HAVE_TYPED_INCORRECT_ACTUAL_PASSWORD_); break;
                    case 5: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_ALL_REQUIRED_VALUES_ARE_NOT_TYPED_); break;
                    case 4: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_i18n_user_NEW_PASSWORD_AND_REPEAT_NEW_PASSWORD_DO_NOT_MATCH_); break;
                }
                
            }
        }
        //----------------------------------------------------------------------


        //----------------------------------------------------------------------
        //show form for input personal (organizational) which are need for sendeing
        //order without registring
        if($sUserOperation == 'jsd_UO_ShowFormToMAkeOrderWithoutRegistring'){
            aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getUserFormToMakeOrderWithoutRegistring()));
        }
        //----------------------------------------------------------------------

        //----------------------------------------------------------------------
        //Retrieve personal information for sending order without registring,
        //check data integrity and try to make session
        if($sUserOperation == 'jsd_UO_InsertDataToSessToMakeOrderWithoutRegistring'){
            $aasValues    = $this->makeAssocArrayForUser();
            $bTestResult  = $this->TestBeforeUserInfoUpdating($aasValues);
            if ($bTestResult==1){
                //create session
                $_UserData = new classUsersData();
                $_UserData->InsertDataToSession($aasValues);
                aprint('flow_container2',$_Window->ShowByAJAX('flow_container2',$_Form->getSaveToSessionSuccessfullInfo()));
            }
            else {
                switch($bTestResult){
                    case 5: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_ALL_REQUIRED_VALUES_ARE_NOT_TYPED_); break;
                    case 4: aprint('User_RegisterForm_Test_Result_Container',_i18n_user_YOU_HAVE_TO_TYPE_LEAST_ONE_OF_FIELDS_MARKED_BY_2STARS_); break;
                }

            }
        }
        //----------------------------------------------------------------------


        //----------------------------------------------------------------------
        //Delete personal information from session with personal data (data to
        //sending order without registring)
        if($sUserOperation == 'jsd_UO_DeleteDataFromSessToMakeOrderWithoutRegistring'){
              $_UserData = new classUsersData();
              $_UserData->DeleteSessionData();
        }
        //----------------------------------------------------------------------
        
        
        //-----------------------serialize session------------------------------
        $_user_sess->serializeIt($this->user_sess_value);
        //----------------------------------------------------------------------
    }
    
    public function getUserMenu($iIsLogged){
        $_Form = new classUsersForms();
        if($iIsLogged==true){
            $_UserData = new classUsersData();
            $aasValue = $_UserData->getUserInfo($this->user_sess_value);             
            return $_Form->getUserMenu_AfterLogin($aasValue['U_Name'].' '.$aasValue['U_Surname']);
        }
        else
            return $_Form->getUserMenu_BeforeLogin();
    }
    
    private function makeAssocArrayForUser(){
        $_Input = new classInput();
        
        $aasValues['U_Organisation']  = $_Input->Sterilize(trim($this->User_RegisterForm_U_Organisation));
        $aasValues['U_Name']          = $_Input->Sterilize(trim($this->User_RegisterForm_U_Name));
        $aasValues['U_Surname']       = $_Input->Sterilize(trim($this->User_RegisterForm_U_Surname));
        $aasValues['U_City']          = $_Input->Sterilize(trim($this->User_RegisterForm_U_City));
        $aasValues['U_Street']        = $_Input->Sterilize(trim($this->User_RegisterForm_U_Street));
        $aasValues['U_PostID']        = $_Input->Sterilize(trim($this->User_RegisterForm_U_PostID));
        $aasValues['U_Mobile']        = $_Input->Sterilize(trim($this->User_RegisterForm_U_Mobile));
        $aasValues['U_Phone']         = $_Input->Sterilize(trim($this->User_RegisterForm_U_Phone));
        $aasValues['U_Email']         = $_Input->Sterilize(trim($this->User_RegisterForm_U_Email));
        $aasValues['U_BirthDate']     = $_Input->Sterilize(trim($this->User_RegisterForm_U_BirthDate));
        $aasValues['U_ICO']           = $_Input->Sterilize(trim($this->User_RegisterForm_U_ICO));
        $aasValues['U_DIC']           = $_Input->Sterilize(trim($this->User_RegisterForm_U_DIC));
        $aasValues['U_Nick']          = $_Input->Sterilize(trim($this->User_RegisterForm_U_Nick));
        $aasValues['U_Passwd']        = $_Input->Sterilize(trim($this->User_RegisterForm_U_Passwd));
        $aasValues['U_Passwd2']       = $_Input->Sterilize(trim($this->User_RegisterForm_U_Passwd2));
        return $aasValues;
    }
    
    private function TestBeforeSaving($aasValues){ //association array of strings = aas :)
        //test, if requested data are typed
        if(
            $aasValues['U_Name']    == '' or
            $aasValues['U_Surname'] == '' or
            $aasValues['U_City']    == '' or
            $aasValues['U_Street']  == '' or
            $aasValues['U_PostID']  == '' or
            $aasValues['U_Nick']    == '' or
            $aasValues['U_Passwd']  == '' or
            $aasValues['U_Passwd2'] == ''
        )
          return 5;
          
        //test, if requested data are typed (1 field from 2)
        if(
            $aasValues['U_Mobile']  == '' and
            $aasValues['U_Phone']   == '' 
        )
          return 4;
          
        //password test
        if($aasValues['U_Passwd'] !=  $aasValues['U_Passwd2'])
          return 3;
          
        //login name test (test, whether typed login name isnt saved in DB, yet)
        $_UserData = new classUsersData();        
        if($_UserData->NickNameCheck($aasValues['U_Nick'])>0)
          return 2;
          
        //if all test are negative (data are typed successfull):
        return 1;
    }
    
    private function TestBeforeUserInfoUpdating($aasValues){ //association array of strings = aas :)
        //test, if requested data are typed
        if(
            $aasValues['U_Name']    == '' or
            $aasValues['U_Surname'] == '' or
            $aasValues['U_City']    == '' or
            $aasValues['U_Street']  == '' or
            $aasValues['U_PostID']  == '' 
        )
          return 5;
          
        //test, if requested data are typed (1 field from 2)
        if(
            $aasValues['U_Mobile']  == '' and
            $aasValues['U_Phone']   == '' 
        )
          return 4;
          
        //if all test are negative (data are typed successfull):
        return 1;
    }
    
    private function TestBeforeUserPasswordUpdating($iUID,$sOldPassword,$sNewPassword,$sNewPassword2){         
        //test, if requested data are typed
        if(
            $sOldPassword    == '' or
            $sNewPassword    == '' or
            $sNewPassword2   == ''
        )
          return 5;
          
        //test, if requested old password match with data in DB
        $_UserData = new classUsersData();
        if($_UserData->PasswordCheck($iUID, $sOldPassword)!=1)
          return 6;
          
        //test, if requested data match (1 field from 2)
        if($sNewPassword != $sNewPassword2)
          return 4;
          
        //if all test are negative (data are typed successfull):
        return 1;
    }


    //function for sending forgtet password

    private function sendEmailWithNewPassword($sUserNickname){

        function getDateExpDate(){
            $order_date = getdate();
            $month = $order_date['mon'];
            $mday = $order_date['mday'];
            $year = $order_date['year'];
            return date(_DB_SERVER_LOCAL_DATE_FORMAT_,mktime(0,0,0,$month,($mday + _EXPIRATION_OF_GENERATED_PASSWORD_IN_DAYS_),$year));
        }
        
        function generateRndString($iStrLen){
            // start with a blank password
            $rnd_str = "";
            // define possible characters
            $possible = "0123456789abcdfghjkmnpqrstvwx";
            // set up a counter
            $i = 0;     
            // add random characters to $rnd_str until $length is reached
            while ($i < $iStrLen) { 
                // pick a random character from the possible ones
                $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);        
                // we don't want this character if it's already in the password
                if (!strstr($rnd_str, $char)) { 
                    $rnd_str .= $char;
                    $i++;
                }
            }
            return $rnd_str;
        }

        function getEmail($iUserID){
            if(trim($iUserID)!='' and is_numeric($iUserID) and $iUserID>0){
                $_UserData = new classUsersData();
                $asUserData = $_UserData->getUserInfo($iUserID);
                if(trim($asUserData['U_Email'])!='')
                    return $asUserData['U_Email'];
                else return '_NO_EMAIL_ADDRESS_';
            }            
            else return '_NO_EMAIL_ADDRESS_';
        }

        function duplicityTest($iUserID){
            if(trim($iUserID)!='' and is_numeric($iUserID) and $iUserID>0){
                $_UserData = new classUsersData();
                return $_UserData->ForgottenPasswdDuplicityTest($iUserID);
            }
            return 0;
        }

        function getUrl($sIdentifier){
            return 'http://'.$_SERVER["HTTP_HOST"].'/npsswd.php?identifier='.$sIdentifier;
        }

        //--*body of function*--

        //test if username exists
        $_UserData = new classUsersData();
        $iUserID = $_UserData->geUserID(trim($sUserNickname));
        if(!(trim($iUserID)!='' and is_numeric($iUserID) and $iUserID>0))
            return '_USER_DONT_EXISTS_';

        //test if user has registered email
        $sEmail = getEmail($iUserID);
        if($sEmail=='_NO_EMAIL_ADDRESS_')
            return $sEmail;

        //test duplicity of sending new password on the same eccount
        $Duplicity = duplicityTest($iUserID);
        if(trim($Duplicity)!='' and is_numeric($Duplicity) and $Duplicity>0){
            return '_DUPLICITY_ERROR_';
        }

        $Date = getDateExpDate();
        $NewPassword = generateRndString(_LENGTH_OF_GENERATED_PASSWORD_);
        $Identifier = sha1($Date.$NewPassword.generateRndString(5).$sUserNickname);

        $_UserForm = new classUsersForms();
        mail(
            $sEmail,
			_i18n_user_CONFIRM_YOUR_NEW_PASSWORD_,
            $_UserForm->getForgottenPasswd_Email_Body($NewPassword, getUrl($Identifier), $_SERVER['REMOTE_ADDR'], date(_CLIENT_LOCAL_DATE_FORMAT_.', '._CLIENT_LOCAL_TIME_FORMAT_)),
            "Content-Type: text/html; charset=utf-8"
        );
        
        $SQL = $_UserData->ForgottenPasswd_SaveNewPassword($iUserID, $Date, $Identifier, $NewPassword);

        return '_SUCCESSFULL_';
    }
}
?>
